package com.yunhui.service.mq;



import com.rabbitmq.client.Channel;
import com.yunhui.entity.Order;
import com.yunhui.entity.PeopleInfo;
import com.yunhui.entity.SubscribePeople;
import com.yunhui.mapper.OrderMapper;
import com.yunhui.service.RouteIssuedService;
import com.yunhui.service.RouteJbService;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.List;


@RabbitListener(queues="queueorder")
@Service
public class MQOrderService {


    @Resource
    private RouteIssuedService routeIssuedService;


    //行程基本信息业务层
    @Resource
    private RouteJbService routeJbService;


    @Resource
    private OrderMapper orderMapper;



    @RabbitHandler
    public void addOrder(Object [] objects, Channel channel, Message message) {
        //System.err.println(asd);
       // Order order, SubscribePeople subscribePeople, List<PeopleInfo> list
     //   Object [] hun = ( Object [])objects;
        Order order =  (Order) objects[0];
        SubscribePeople subscribePeople = (SubscribePeople)objects[1];
        @SuppressWarnings("unchecked")
		List<PeopleInfo> list = ( List<PeopleInfo> )objects[2];

        System.err.println("执行添加行程");
        try {
            //boolean num = false ;

            //用户人数
            int userNum = list.size();

            //获取行程基础总人数
            int jiNum =routeJbService.getById(routeIssuedService.getById(order.getSid()).getJbId()).getMaxPerson();

            int countFaCount = routeIssuedService.selectByJbId(order.getSid());
            //判断超过总人数
            if((userNum+countFaCount)>=jiNum){
                return ;
            }

            //首先添加订单
            orderMapper.insert(order);
            subscribePeople.setO_id(order.getId());
            //添加订单联系人
            orderMapper.addSubscribePeople(subscribePeople);

            //循环添加订单出行人信息
            for(PeopleInfo p:list){
                //添加订单编号
                p.setO_id(order.getId());
                orderMapper.addPeopleInfo(p);
            }

        } catch (Exception e) {
            //这段代码表示，这次消息，我已经接受并消费掉了，不会再重复发送消费
            try {
                channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
            } catch (IOException e1) {
                // TODO Auto-generated catch block
                e1.printStackTrace();
            }
        }
    }
}
